// pages/modifyUser/modifyUser.js
const app = getApp();

Page({
    data: {
        avatarUrl: '',
        nickName: '',
        nickNameError: '',
        isLoading: false,
        userId: '',
        cloudAvatarUrl: ''
    },

    onLoad: function (options) {
        // 加载用户信息
        this.loadUserInfo();
    },

    onShow: function () {
        // 页面显示时重新加载用户信息
        this.loadUserInfo();
    },

    // 加载用户信息
    loadUserInfo: function () {
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({
                avatarUrl: userInfo.avatarUrl || '',
                nickName: userInfo.nickName || '',
                userId: userInfo._id || ''
            });
        } else {
            wx.showToast({
                title: '获取用户信息失败',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        }
    },

    // 选择头像
    onChooseAvatar: function (e) {
        // console.log(e);
        const avatarUrl = e.detail.avatarUrl;
        this.setData({
            avatarUrl: avatarUrl
        });
        const ext = avatarUrl.match(/\.[^.]+?$/)[0];
        const cloudPath = `avatar/${Date.now()}${ext}`;
        wx.cloud.uploadFile({
            cloudPath: cloudPath, // 上传至云端的路径
            filePath: avatarUrl, // 小程序临时文件路径
            success: res => {
                // 返回文件 ID
                // console.log(res)
                this.setData({
                    cloudAvatarUrl: res.fileID
                })
            },
            fail: err => {
                console.log(err)
            }
        })
    },

    //获取昵称
    formsubmit(e) {
        // console.log(e.detail.value.nickname);
        this.setData({
            nickName: e.detail.value.nickname
        })
        this.saveUserInfo()
    },
    // 保存用户信息
    saveUserInfo: function () {
        // console.log(this.data);
        const {
            avatarUrl,
            nickName,
            userId,
            cloudAvatarUrl
        } = this.data;


        // 验证昵称
        if (!nickName || nickName.length < 2 || nickName.length > 20) {
            wx.showToast({
                title: '昵称长度需在2-20字符之间',
                icon: 'none'
            });
            return;
        }
        // 头像
        if (!cloudAvatarUrl ) {
            wx.showToast({
                title: '请选择头像',
                icon: 'none'
            });
            return;
        }
        // 显示加载状态
        this.setData({
            isLoading: true
        });

        // 调用云函数更新用户信息
        wx.cloud.callFunction({
          name: 'updateUserInfo',
          data: {
            userId: userId,
            avatarUrl: cloudAvatarUrl,
            nickName: nickName
          }
        }).then(res => {
          if (res.result.success) {
            // 更新本地存储的用户信息
            const currentUserInfo = wx.getStorageSync('userInfo') || {};
            wx.setStorageSync('userInfo', {
              ...currentUserInfo,
              avatarUrl: cloudAvatarUrl,
              nickName: nickName
            });
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            });

            // 返回上一页
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          } else {
            wx.showToast({
              title: res.result.message || '保存失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          console.error('更新用户信息失败', err);
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }).finally(() => {
          this.setData({
            isLoading: false
          });
        });
    }
});